package com.zhiyume.service;

import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.dao.api.TInformationMapper;
import com.zhiyume.dao.api.TInformationSelfMapper;
import com.zhiyume.dao.entity.TInformationCriteria;
import com.zhiyume.dao.entity.TInformationWithBLOBs;
import com.zhiyume.oss.OssUpload;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.GenerateKeyUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import static com.zhiyume.util.TypeConstants.StyleConstants.*;

/**
 * 资讯相关操作
 */
@Service
@Transactional
public class InformationService {

    @Autowired
    TInformationMapper informationMapper;
    @Autowired
    TInformationSelfMapper informationSelfMapper;

    private static final Logger logger = LoggerFactory.getLogger(InformationService.class);

    /**
     * 资讯保存
     * @param information
     */
    public void addInformation(TInformationWithBLOBs information){
        information.setId(GenerateKeyUtil.generationPK());
        information.setCreateTime(DateUtil.getNow());
        information.setUpdateTime(DateUtil.getNow());

//        // 状态: 0-草稿 1-待审核
//        if(StringUtil.isBlank(String.valueOf(information.getStatus()))){
//            information.setStatus(1);
//        }
//        // 状态值
//        if(StringUtil.isBlank(information.getStatusValue())){
//            information.setStatusValue("待审核");
//        }

        // 楼层
        if(StringUtil.isBlank(information.getVideoUrl())){
            //information.setFloorType(TypeConstans.IMAGE_FLOOR.getType());
            information.setFloorType(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR));
        }else{
            //information.setFloorType(TypeConstans.VIDEO_FLOOR.getType());
            information.setFloorType(TypeConstants.floorMap.get(TypeConstants.VIDEO_FLOOR));
        }
        //默认不推荐资讯
        information.setIsIntro(1);
        //默认资讯可现实
        information.setIsShow(0);


        String imgUrl = information.getCoverUrl();
        String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
        List<String> urls = genAppImg(imgUrls,information.getFloorType(),information.getImgStatus().toString());
        if(CollectionUtils.isNotEmpty(urls)){
            if(urls.size()==1){
                information.setCoverUrl1(urls.get(0));
            }else
            if(urls.size()==2){
                information.setCoverUrl1(urls.get(0));
                information.setCoverUrl2(urls.get(1));
            }else
            if(urls.size()==3){
                information.setCoverUrl1(urls.get(0));
                information.setCoverUrl2(urls.get(1));
                information.setCoverUrl3(urls.get(2));
            }
        }

        informationMapper.insert(information);
    }

    /**
     * 获取所有资讯列表
     * @return
     */
    public Map findAllInformationList(int page, int pageSize,String title){
        TInformationCriteria example = new TInformationCriteria();
        TInformationCriteria.Criteria c = example.createCriteria();

        if(title != null && !"".equals(title)) c.andTitleLike("%" + title + "%");
        int count = informationMapper.countByExample(example);

        example.setLimitStart(page*pageSize);
        example.setLimitEnd(pageSize);

        List<TInformationWithBLOBs> list = informationMapper.selectByExampleWithBLOBs(example);

        Map dataMap = new HashMap();
        dataMap.put("list",list);
        dataMap.put("total",count);
        dataMap.put("page",page);
        return dataMap;
    }

    /**
     * 使用自定义mapper查询资讯列表
     * @param page
     * @param pageSize
     * @param title
     * @param startTime
     * @param endTime
     * @return
     */
    public Map findAllInformationList(int page, int pageSize,String title,String navType,String startTime,String endTime){
        Map pMap = new HashMap();

        pMap.put("page",page*pageSize);
        pMap.put("pageSize",pageSize);
        pMap.put("title",title);
        pMap.put("navType",navType);
        pMap.put("startTime",startTime);
        pMap.put("endTime",endTime);

        int cnt = informationSelfMapper.selectInformationCntByTitle(pMap);

        List<TInformationWithBLOBs> list = informationSelfMapper.selectInformationListByTitle(pMap);

        Map dataMap = new HashMap();
        dataMap.put("list",list.size() == 0 ? null : list);
        dataMap.put("total",cnt);
        dataMap.put("page",page);
        return dataMap;
    }

    /**
     * 根据id获取资讯
     */
    public TInformationWithBLOBs findInfoById(long id){
        TInformationCriteria example = new TInformationCriteria();
        TInformationCriteria.Criteria c = example.createCriteria();
        c.andIdEqualTo(id);
        List<TInformationWithBLOBs> list = informationMapper.selectByExampleWithBLOBs(example);
        if(list.size() > 0) return list.get(0);
        return null;
    }

    /**
     * 更新information
     */
    public void updateInformation(TInformationWithBLOBs information){
        // 更新时间
        information.setUpdateTime(DateUtil.getNow());
        //informationMapper.updateByExampleWithBLOBs(information,example);
        informationMapper.updateByPrimaryKeySelective(information);
    }

    /**
     * 获取待审核资讯列表
     * @param page
     * @param pageSize
     * @param title
     * @param startTime
     * @param endTime
     * @return
     */
    public Map findCheckPendingList(int page, int pageSize,String title,String startTime,String endTime){
        Map pMap = new HashMap();
        pMap.put("page",page*pageSize);
        pMap.put("pageSize",pageSize);
        pMap.put("title",title);
        pMap.put("startTime",startTime);
        pMap.put("endTime",endTime);
        pMap.put("status",TypeConstants.statusMap.get(TypeConstants.STATUS_CHECKPENDING));

        int cnt = informationSelfMapper.selectInformationCntByTitle(pMap);

        List<TInformationWithBLOBs> list = informationSelfMapper.selectInformationListByTitle(pMap);

        Map dataMap = new HashMap();
        dataMap.put("list",list.size() == 0 ? null : list);
        dataMap.put("total",cnt);
        dataMap.put("page",page);
        return dataMap;
    }


    /**
     * 获取已发布资讯列表
     * @param page
     * @param pageSize
     * @param title
     * @param startTime
     * @param endTime
     * @return
     */
    public Map findPublishedList(int page, int pageSize,String title,int navType,String startTime,String endTime){
        Map pMap = new HashMap();
        pMap.put("page",page*pageSize);
        pMap.put("pageSize",pageSize);
        pMap.put("title",title);
        pMap.put("navType",navType);
        pMap.put("startTime",startTime);
        pMap.put("endTime",endTime);
        pMap.put("status",TypeConstants.statusMap.get(TypeConstants.STATUS_PUBLISHED));

        int cnt = informationSelfMapper.selectInformationCntByTitle(pMap);

        List<TInformationWithBLOBs> list = informationSelfMapper.selectInformationListByTitle(pMap);

        Map dataMap = new HashMap();
        dataMap.put("list",list.size() == 0 ? null : list);
        dataMap.put("total",cnt);
        dataMap.put("page",page);
        return dataMap;
    }

    /**
     * 获取审核未通过资讯列表
     * @param page
     * @param pageSize
     * @param title
     * @param startTime
     * @param endTime
     * @return
     */
    public Map findFailedList(int page, int pageSize,String title,String startTime,String endTime){
        Map pMap = new HashMap();
        pMap.put("page",page*pageSize);
        pMap.put("pageSize",pageSize);
        pMap.put("title",title);
        pMap.put("startTime",startTime);
        pMap.put("endTime",endTime);
        pMap.put("status",TypeConstants.statusMap.get(TypeConstants.STATUS_FAILED));

        int cnt = informationSelfMapper.selectInformationCntByTitle(pMap);

        List<TInformationWithBLOBs> list = informationSelfMapper.selectInformationListByTitle(pMap);

        Map dataMap = new HashMap();
        dataMap.put("list",list.size() == 0 ? null : list);
        dataMap.put("total",cnt);
        dataMap.put("page",page);
        return dataMap;
    }

    /**
     * 更新稿件状态
     */
    public void updateInformationStatus(long id,String status){
        Map map = new HashMap();
        if(TypeConstants.statusMap.get(TypeConstants.STATUS_PUBLISHED).equals(status)){
            // 更新时间
            map.put("publishTime",DateUtil.getNow());
            map.put("updateTime",DateUtil.getNow());
            map.put("id",id);
            map.put("status",status);
            map.put("statusValue",TypeConstants.statusMap.get(status));
        }else{
            // 更新时间
            map.put("updateTime",DateUtil.getNow());
            map.put("id",id);
            map.put("status",status);
            map.put("statusValue",TypeConstants.statusMap.get(status));
        }
        informationSelfMapper.updateInformationStatus(map);
    }

    /**
     * 获取推荐资讯列表(暂定为id与当前不同的,按id倒序取5个)
     * @param id
     * @param limit 限制获取的条数
     * @return
     */
    public List<TInformationWithBLOBs> getIntroInformationList(long id, int limit){
        Map map = new HashMap();
        map.put("id",id);
        map.put("limit",limit);
        List<TInformationWithBLOBs> list = informationSelfMapper.getIntroInformationList(map);
        return list;
    }


    /**
     * deleteInformationById
     */
    public void deleteInformationById(long id){
        TInformationCriteria example = new TInformationCriteria();
        TInformationCriteria.Criteria c = example.createCriteria();
        c.andIdEqualTo(id);
        informationMapper.deleteByExample(example);
    }


    /**
     * 更新操作相关状态(置顶,推荐,下架,撤回重审)
     * @param id
     * @param statusType 操作类型
     * @param statusValue 操作类型值
     * @return
     */
    public void updateInformationOptStatus(long id,String statusType,String statusValue){
        TInformationWithBLOBs information = this.findInfoById(id);
        Map map = new HashMap();
        map.put("id",id);
        map.put("updateTime",DateUtil.getNow());


        if(TypeConstants.OPT_TO_TOP.equals(statusType) || TypeConstants.OPT_SLIDER.equals(statusType)){
            if("".equals(statusValue) || statusValue == null || statusValue == "null"){
                // 楼层
                if(StringUtil.isBlank(information.getVideoUrl())){
                    statusValue = TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR);
                }else{
                    statusValue = TypeConstants.floorMap.get(TypeConstants.VIDEO_FLOOR);
                }

            }else if(TypeConstants.OPT_TO_TOP.equals(statusType)){
                //statusValue = TypeConstants.floorMap.get(TypeConstants.TOP_FLOOR);

                //
                Map temp = new HashMap<>();
                temp.put("floorType",TypeConstants.floorMap.get(TypeConstants.TOP_FLOOR));
                temp.put("limit",1);
                if(TypeConstants.AppConstants.IF_INTRO!=information.getIsIntro()){
                    temp.put("navType",information.getNavType());
                }else if(TypeConstants.AppConstants.IF_INTRO==information.getIsIntro()){
                    temp.put("isIntro",information.getIsIntro());
                }
                Map result = informationSelfMapper.selectSpecifyTime(temp);


                int count =Integer.valueOf(result.get("slidecount").toString());
                if(count==1){
                    String updateTime =result.get("slidetime").toString();
                    temp.put("updateTime",updateTime);
                    updateMyStatus(temp);
                }

            }else{
                //statusValue = TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR);

                Map temp = new HashMap<>();
                temp.put("floorType",TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR));
                temp.put("limit",6);
                if(TypeConstants.AppConstants.IF_INTRO!=information.getIsIntro()){
                    temp.put("navType",information.getNavType());
                }else if(TypeConstants.AppConstants.IF_INTRO==information.getIsIntro()){
                    temp.put("isIntro",information.getIsIntro());
                }

                Map result = informationSelfMapper.selectSpecifyTime(temp);


                int count =Integer.valueOf(result.get("slidecount").toString());
                if(count==6){
                    String updateTime =result.get("slidetime").toString();
                    temp.put("updateTime",updateTime);
                    updateMyStatus(temp);
                }
            }
            map.put("floorType",statusValue);
        }else if(TypeConstants.OPT_UNDER.equals(statusType)){
            map.put("isShow",statusValue);
        }else if(TypeConstants.OPT_INTRO.equals(statusType)){
            map.put("isIntro",statusValue);
        }else if(TypeConstants.OPT_REVOKE.equals(statusType)){
            updateInformationStatus(id,statusValue);
            return;
        }

        informationSelfMapper.updateInformationOptStatus(map);
    }

    private void updateMyStatus(Map temp) {
        if(temp.get("updateTime")!=null){
            String updateTime = (temp.get("updateTime").toString());
            if(StringUtil.isNotBlank(updateTime)){
                temp.put("imgStatus",13);
                temp.put("updateTime", updateTime);
                informationSelfMapper.updateTopOrSliderStatus(temp);
            }
        }
    }

    //拼装数据
//    public String saveAppImgUrl(String imgUrl,String code){
//        String url = "";
//        String splitFlag = "?";
//        String nameSplitFlag = ".com";
//        if(TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR).equals(code)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,slider_style);
//        }else if(TypeConstants.floorMap.get(TypeConstants.TOP_FLOOR).equals(code)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,video_style);
//        }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
//                && TypeConstants.floorMap.get(TypeConstants.IMAGE_BIG_FLOOR).equals(imgStatus)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,slider_style);
//        }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
//                && TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(imgStatus)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,img_style);
//        }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
//                && TypeConstants.floorMap.get(TypeConstants.IMAGE_LR_FLOOR).equals(imgStatus)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,video_style);
//        }else if(TypeConstants.floorMap.get(TypeConstants.VIDEO_FLOOR).equals(code)){
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,video_style);
//        }else{
//            url = genOneAppImgUrl(imgUrl, splitFlag, nameSplitFlag,img_style);
//        }
//
//        return url;
//    }
//
//    private String genOneAppImgUrl(String url,String splitFlag,String nameSplitFlag,String style){
//        String img = "";
//        String[] nameArr;
//        try{
//            //在传参需要处理特殊字符
//            nameArr = URLDecoder.decode(url,"utf-8").split(nameSplitFlag);
//            String imgName = nameArr[1].substring(1, nameArr[1].indexOf(splitFlag));
//            img = OssUpload.getImgStyleUrl(style,imgName);
//        }catch (UnsupportedEncodingException e){
//            logger.error(e.getMessage());
//        }
//
//        return img;
//    }


    public List<String> genAppImg(String[] imgUrls,String code,String imgStatus){

        List<String> urls = new ArrayList<>();
        String splitFlag = "?";
        String nameSplitFlag = ".com";
        if(!CollectionUtils.isEmpty(Arrays.asList(imgUrls))){
            try {
                if(TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,slider_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.TOP_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(TypeConstants.IMAGE_BIG_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,slider_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,img_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(TypeConstants.IMAGE_LR_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.VIDEO_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else{
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,img_style);
                }
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        return urls;
    }

    public List<String> genAppImgUrl(String[] imgUrls, String splitFlag, String nameSplitFlag,String style)
    throws Exception{
        List<String> urls = new ArrayList<>();
        String[] nameArr;
        for (String url : imgUrls){

            if(StringUtil.isBlank(url)) {
                urls.add("");
            }else{
                //在传参需要处理特殊字符
                nameArr = URLDecoder.decode(url,"utf-8").split(nameSplitFlag);
                String imgName = nameArr[1].substring(1, nameArr[1].indexOf(splitFlag));
                urls.add(OssUpload.getImgStyleUrl(style,imgName));
            }

        }
        return urls;
    }

}
